import { spawn } from 'child_process';
import fs from 'fs'
import { apppack, save_xml, save_python, save_json, build_path, pythonweb } from '../file/file'
import { pythonname } from '../utils/local';
import { port } from '../utils/web';

const web = `#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import web
import serial
import serial.tools.list_ports
import time


plist = list(serial.tools.list_ports.comports())
t = False
serialName = ''
for i in plist:
    if i.vid and int(i.vid) == 6790:
        t = True
        serialName = i.device


if t == False:
    raise NameError('没有找到设备')

serialFd = serial.Serial(serialName, 9600, timeout=60)

urls = (
    '/(.*)', 'hello'
)

app = web.application(urls, globals())


class hello:
    def POST(self, name):
        i = web.input(str="")
        st = i.get('str')
        ty = i.get('type')
        # 用type区分是否是数组字符串
        if ty:
            f = i.get('read')
            # 用read来读取设备信息
            if f:
                serialFd.write(bytes(f, 'utf-8'))
                time.sleep(0.05)
                if serialFd.readable():
                    str1 = serialFd.read_all()
                    return str1
            else:
                serialFd.write(bytes(st, 'utf-8'))
        else:
            b = st.split('-')
            for o in b:
                serialFd.write(bytes(o, 'utf-8'))
                time.sleep(0.3)
        return 'Hello, ' + name + '!'

    def GET(self):
        return 'Hello, !'


if __name__ == "__main__":
    app.run()

`

export default function init() {
  if (!fs.existsSync(apppack)) {
    fs.mkdirSync(apppack);
  }
  if (!fs.existsSync(save_xml)) {
    fs.mkdirSync(save_xml);
  }
  if (!fs.existsSync(save_python)) {
    fs.mkdirSync(save_python);
  }
  if (!fs.existsSync(save_json)) {
    fs.mkdirSync(save_json);
  }
  if (!fs.existsSync(build_path)) {
    fs.mkdirSync(build_path);
  }
  fs.promises.writeFile(pythonweb, web)
}

export async function Portweb() {
  const python = await pythonname()
  const ls = spawn(python, ["-u", pythonweb, port])
  return ls
}